#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

class RouterRegister {

    basePath = './../src/shared';
    replaceName = '';

    constructor(base = './../src/shared') {
        this.basePath = base;
    }

    routerRegister() {
        const basePath = path.join(__dirname, this.basePath);
        const files = this.getFiles(basePath);
        files.forEach((fileName) => {
            const content = this.getFileData(fileName)
            const regex = /(\/\*[\S\s]+?Copyright[\S\s]+?\*\/)|(\/\/ Copyright[\S\s]+?\r\n)/ig;
            let result = content.replace(regex, this.replaceName).trimStart();
            this.writeFile(result, fileName);
        });
        console.log('finish---->end');
    }

    getFileData(filePath) {
        if (!fs.existsSync(filePath)) {
            return '';
        }
        return fs.readFileSync(filePath, { encoding: 'utf-8' });
    }

    writeFile(dataResult, fileName) {
        let fd = fs.openSync(fileName, 'w');
        fs.writeFileSync(fd, dataResult, 'utf-8');
        fs.closeSync(fd);
    }

    getFiles(controllerPath) {
        const routers = [];
        if (!fs.existsSync(controllerPath)) {
            return [];
        }
        const files = fs.readdirSync(controllerPath);
        files.forEach((currentFile) => {
            const routerFile = path.join(controllerPath, currentFile);
            if (fs.statSync(routerFile).isDirectory()) {
                routers.push(...this.getFiles(routerFile));
            } else {
                routers.push(routerFile);
            }
        });
        return routers;
    }
}

new RouterRegister().routerRegister();
